package com.qf.controller;

import com.qf.service.ItemService;
import com.qf.util.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 商品模块的controller
 */
@Controller
@RequestMapping("/item")
public class ItemController {

    @Autowired
    private ItemService itemService;



    //添加商品
    @RequestMapping("/add")
    public String add(MultipartFile picFile, HttpServletRequest req) throws IOException {

        System.out.println("ttttttttttttttttttttttt");

        if(picFile != null) {
            System.out.println("12334664665");
           //1.给图片重新起一个新名字
            //1.1获取图片原名字
            String filename = picFile.getOriginalFilename();
            //1.2使用lang3下的StringUtils获取图片最后一个.后面的全部内容
            String typeName = StringUtils.substringAfterLast(filename, ".").toLowerCase();
            //1.3起个新名字
            String prefixName = UUID.randomUUID().toString();
            String newName =prefixName + "." + typeName;
            //2.将图片保存到本地
            File file = new File(req.getServletContext().getRealPath("/static/images/"+ newName));
            picFile.transferTo(file);
            //3.封装一个访问路径
            String pic = "http://localhost/static/images/" + newName;
            System.out.println(pic);
        }
            return "item/item_add";

    }

    //展示商品
    @RequestMapping("/list")
    public String list(@RequestParam(value = "page",defaultValue = "1")Integer page,
                        @RequestParam(value="size",defaultValue = "5")Integer size,
                        String name,
                        Model model ){
        //1.调用service查询商品和分页信息
        PageInfo pageInfo=itemService.findItemByCondition(name,page,size);
        model.addAttribute("pageInfo",pageInfo);

        //2.为了数据回显
        model.addAttribute("name",name);

        //3.转发到商品展示页面
        return "item/item_list";
    }
}
